<?php
defined('IN_PHPCMS') or exit('No permission resources.');
// 模型缓存路径
define('CACHE_MODEL_PATH', CACHE_PATH . 'caches_model' . DIRECTORY_SEPARATOR . 'caches_data' . DIRECTORY_SEPARATOR);
// 定义在单独操作内容的时候，同时更新相关栏目页面
define('RELATION_HTML', true);

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);

/**
 * 资源赛事管理
 */
class contest extends admin
{

    private $db,$type,$csmodel;

    public $siteid;

    public function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('news_nsr_model');
        $this->type = pc_base::load_model('source_type_model');
        $this->csmodel = pc_base::load_model('contest_source_model');
        $this->siteid = get_siteid();
        $model_setting=pc_base::load_model('site_setting_model');
        $this->type= $model_setting->getValue("contest_type",$this->siteid);
    }

    /**
     * 资讯绑定赛事列表
     */
    public function index()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $show_dialog = $show_validator = true;
        $show_header = '';
        $id= $_REQUEST['id'];
        $source_type = $_REQUEST['source_type'];
        if ($source_type == 1) {
            $info = $this->db->get_one(array('id' => $id));
        } else if($source_type == 2){
            $video_model = pc_base::load_model('video_nsr_model');
            $info = $video_model->get_one(array('id' => $id));
        } else if($source_type == 3){
            $picture_model = pc_base::load_model('picture_nsr_model');
            $info = $picture_model->get_one(array('id' => $id)); 
        } 

        $sql="select n.*,c.id as cid,c.sort,c.is_top from nsrweb_contest_source as c LEFT JOIN nsrweb_contest as n on c.contest_id =n.id where n.status=1 and c.source_type = " . $source_type;
        $sql .= " and  c.source_id=".$id." and siteid =" . $this->siteid;
        if (isset($_GET['name']) && !empty($_GET['name'])) {
            $name = trim($_GET['name']);
            $sql .= " and `name` like '%$name%' ";
        }
        $sql .= " order by c.is_top desc,c.sort desc ";
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $contestinfo = $this->db->my_listinfo($sql, $page, 10);

        $pages = $this->db->pages;
        include $this->admin_tpl('contest_list');
    }

    /**
     * 添加赛事
     */
    public function add()
    {
        if(isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['created_by'] =  $_SESSION['userid'];
            $data['updated_by'] =  $_SESSION['userid'];
            $data['parentid'] = 0;
            $data['is_child'] = 1;
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['update_time'] = date('Y-m-d H:i:s');
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;
            $contest_model = pc_base::load_model('contest_model');
            $result = $contest_model->insert($data,true);
            if ($result) {
                $data1['created_by'] =  $_SESSION['userid'];
                $data1['updated_by'] =  $_SESSION['userid'];

                $data1['create_time'] = date('Y-m-d H:i:s');
                $data1['update_time'] = date('Y-m-d H:i:s');
                $data1['source_type'] = $_POST['source_type'];
                $data1['source_id'] = $_POST['id'];
                $data1['contest_id'] = $result;
                $res = $this->csmodel->insert($data1);
                if ($res) {
                    showmessage(L('operation_success'), '?m=information&c=contest&a=index&source_type='.$_POST['source_type'].'&id='.$_POST['id'],'','add');
                } else {
                    showmessage(L('operation_failure'), HTTP_REFERER);
                }
            } else {
                showmessage(L('add_error'), HTTP_REFERER);
            }
        } else {
            $source_type = $_REQUEST['source_type'];
            $show_dialog = $show_validator = true;
            $show_header = '';
            if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
                showmessage(L('illegal_action'), HTTP_REFERER);
            }
            $id= $_REQUEST['id'];
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);
            $action_source="contest";
            $column="contest";
            include $this->admin_tpl('contest_add',"contest");
        }
    }

    /**
     * 资讯修改
     */
    public function edit()
    {
        if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if (isset($_POST['dosubmit']) && !empty($_POST['dosubmit'])) {
            $information = $this->check($_POST['information'], 'edit');
            $ids = $this->db->edit($information, $id);
            //添加缓存
            $this->db->redisCache($id);
            if ($ids) {
                showmessage(L('edit_information_success'), '?m=information&c=information&a=index');
            } else {
                showmessage(L('edit_information_error'), HTTP_REFERER);
            }   
        } else {
            $types = $this->type->getSource(1);
            $info = $this->db->get_one(array('id'=>$id, 'siteid'=>$this->siteid));
            extract($info);
            //获取站点模板信息
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('information_edit');
        }
    }

    /**
     * 删除、批量删除
     */
    public function delete()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];

        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }
        $result = $this->csmodel->delete("id in ('$id')");


        if ($result) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

    /**
     * 排序
     */
    public function listorder() {
        if(isset($_GET['dosubmit'])) {
            foreach($_POST['listorders'] as $id => $listorder) {
                $res = $this->csmodel->update(array('sort'=>$listorder), array('id'=>$id));
            }
            showmessage(L('operation_success'));
        } else {
            showmessage(L('operation_failure'));
        }
    }

    /**
     * 置顶
     */
    public function isTop ()
    {
        if (!isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id= $_REQUEST['id'];
        $is_top = $_REQUEST['is_top'];
        $res = $this->csmodel->update(array('is_top'=>$is_top), array('id'=>$id));

        if ($res) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

    /**
     * 选择赛事绑定
     */
    public function bindContest(){
        $tree = pc_base::load_sys_class('tree');
        $sitelist = getcache('sitelist','commons');
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $categorys = array();
        $id= $_REQUEST['id'];
        $source_type = $_REQUEST['source_type'];
        $contest_array = $this->csmodel->select(array("source_id"=>$id,"source_type"=>$source_type),"contest_id");
        $where = " status = 1 AND siteid = " . $this->siteid ." AND end_time > '" . date('Y-m-d H:i:s') ."' ";
        $ids = array();
        if(!empty($contest_array)){
            foreach ($contest_array as $k => $v) {
                $ids[] = intval($v['contest_id']);
            }
        }
        if (isset($_GET['name']) && !empty($_GET['name'])) {
            $name = trim($_GET['name']);
            $where .= " and `name` like '%$name%' ";
        }
        $contest_model = pc_base::load_model('contest_model');
        $infos = $contest_model->select($where, '*', '', 'id DESC');
        foreach ($infos as $k => $v) {
            if(in_array($v['id'],$ids)) {
                $v['statusid'] = 1;
                $v['statusname'] = '<span style="color:red;">已绑定</span>';
            } else {
                $v['statusid'] = 0;
                $v['statusname'] = '<span style="color:green;">未绑定</span>';
            }
            $categorys[$v['id']] = $v;
        }
        $str  = "<tr onclick='select_list(this,\$id)' class='cu' data='\$statusid' title='click_to_select'>
                    <td align='left'>\$spacer\$name\$display_icon</td>
                    <td >\$year</td>
                    <td>\$begin_time</td>
                    <td>\$end_time</td>
                    <td>\$statusname</td>
                </tr>";
        $tree->init($categorys);
        $categorys = $tree->get_tree(0, $str);
        include $this->admin_tpl('bindContest');
    }

    /**
     * 完成绑定
     */
    public function bindContestAjax(){
        $id= $_REQUEST['id'];
        $source_type = $_REQUEST['source_type'];
        $relation=$_REQUEST['relation'];
        $contest=explode("|",$relation);
        $data=array();
        foreach($contest as $k=>$v){
            $data[$k]['contest_id']=$v;
            $data[$k]['source_id']=$id;
            $data[$k]['source_type']=$source_type;
            $data[$k]['created_by'] =  $_SESSION['userid'];
            $data[$k]['updated_by'] =  $_SESSION['userid'];

            $data[$k]['create_time'] = date('Y-m-d H:i:s');
            $data[$k]['update_time'] = date('Y-m-d H:i:s');
        }
        $res = $this->csmodel->multiInsert($data);
        if($res){
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"选择成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"选择失败"));
        }
    }
}